package com.jia.rpc.proxy;

import cn.hutool.core.io.copy.IoCopier;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.jia.rpc.model.RpcRequest;
import com.jia.rpc.model.RpcResponse;
import com.jia.rpc.serializer.JDKSerializer;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 服务代理（JDK动态代理）
 */
public class ServiceProxy implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //制定序列化器
        JDKSerializer serializer = new JDKSerializer();

        //构造请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();

        //序列化
        byte[] bodyBytes = serializer.serializer(rpcRequest);
        //发送请求
        //todo 这里的地址被硬编码（需要使用注册中心和发现服务机制来解决）
        try(HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
                .body(bodyBytes)
                .execute()){
            byte[] result = httpResponse.bodyBytes();
            //反序列化
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            return rpcResponse.getData();
        }catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
